<template>
  <view class="content">
    <image class="bg" src="https://ainengli.meilianshuke.com/jkhx/answerBg.png" />
    <scroll-view :scroll-top="scrollTop" class="scroll-Y" scroll-y="true">
      <view class="chat_list" ref="chatListRef">
        <view class="default">
          <image class="img_robot" src="https://ainengli.meilianshuke.com/jkhx/robot.png" />
          <view class="text">
            您好！我是您的<text style="color: #00d1b6">AI健康助理小美</text><br />
            我已深入学习大量基础医学知识、权威文献指南等，您可以告诉我您的问题，我会解答您～
          </view>
        </view>
        <view v-for="(item, index) of recordList" :key="index" :class="item.type">
          <image
            class="img_robot"
            v-if="item.type == 'answer' || item.type == 'default'"
            src="https://ainengli.meilianshuke.com/jkhx/robot.png"
          />
          <view class="text">
            <text>
              {{ item.content }}
            </text>
            <!-- <flow-text :text="item.content" @onStop="TextStop()" /> -->
          </view>
        </view>
      </view>
    </scroll-view>
    <view class="ask_input">
      <input
        type="text"
        v-model="inputValue"
        confirm-type="send"
        placeholder="请输入您想要咨询的问题"
      />
      <button @click="sendMessage" class="send">发送</button>
    </view>
  </view>
</template>

<script setup lang="ts">
// import FlowText from '@/module/components/FlowText.vue'
import { reactive, ref } from 'vue'
import { onLoad, onUnload, onHide } from '@dcloudio/uni-app'
import { getChat } from '@/api/websocket'

const chatListRef = ref(null)

const userInfo = ref({})

const scrollTop = ref(0)
const inputValue = ref('')
const recordList = ref([])
const answerWs = reactive({
  ws: null,
  isConnect: false,
  lockReconnect: false,
  result: '',
  finish: true
})
const timer = ref()

onLoad(() => {
  userInfo.value = uni.getStorageSync('userInfo')
  // process.env.NODE_ENV === 'production'
  //   ? 'ws://hpzb.zjxsh.com/ws/chat/ws_chat/' // 萧山医院内网地址
  //   : 'wss://ainengli.hzjrsw.com/ws/chat/ws_chat/'
  //   console.log('ws地址', url)
  answerWs.ws = uni.connectSocket({
    url: getChat(),
    complete: () => {}
  })
  answerWs.ws.onOpen((res) => {
    answerWs.isConnect = true
    // console.log('websocket链接成功', res, answerWs.ws)
  })
  answerWs.ws.onMessage((res) => {
    const obj = JSON.parse(res.data)
    if (obj.final === 0) {
      answerWs.result += obj.answer
      recordList.value[recordList.value.length - 1].content = answerWs.result
    } else {
      answerWs.finish = true
    }
    const query = uni.createSelectorQuery()
    query
      .select('.chat_list')
      .boundingClientRect((res) => {
        scrollTop.value = res.height
      })
      .exec()
  })
  uni.onSocketError(function (res) {
    console.log('WebSocket连接打开失败，请检查！', res)
  })
})
onUnload(() => {
  //   console.log('卸载页面')
  answerWs.ws.close()
})

// 方法
const sendMessage = async () => {
  if (inputValue.value == '') {
    uni.showToast({
      icon: 'none',
      title: '发送内容不能为空！'
    })
    return
  }
  if (answerWs.finish == false) {
    uni.showToast({
      icon: 'none',
      title: '请先等待上一个问题回答结束！'
    })
    return
  }
  webSend()
  await recordList.value.push({
    type: 'question',
    content: inputValue.value
  })
  await recordList.value.push({
    type: 'answer',
    content: '回答生成中...'
  })

  inputValue.value = ''
  // 赋值行为在数组插入前，因此使用async await等待内容长度变化再改变滚动高度
  const query = uni.createSelectorQuery()
  query
    .select('.chat_list')
    .boundingClientRect((res) => {
      scrollTop.value = res.height
    })
    .exec()
}
const webSend = () => {
  const askList: any = []
  const answerList: any = []
  const historyList = []
  recordList.value.forEach((item) => {
    if (item.type == 'question') {
      askList.push(item)
    } else if (item.type == 'answer') {
      answerList.push(item)
    }
  })
  for (let i = 0; i < askList.length; i++) {
    historyList.push({
      query: askList[i].content,
      answer: answerList[i].content
    })
  }
  const param = JSON.stringify({
    name: userInfo.value.name || '',
    openId: userInfo.value.openId || '',
    sex: userInfo.value.gender == 2 ? '女' : '男',
    type: 'chat',
    query: inputValue.value,
    history: historyList
  })
  answerWs.result = ''
  answerWs.finish = false
  answerWs.ws.send({
    data: param
  })
}
const TextStop = () => {
  clearInterval(timer.value)
  const query = uni.createSelectorQuery()
  query
    .select('.chat_list')
    .boundingClientRect((res) => {
      scrollTop.value = res.height
    })
    .exec()
}
</script>

<style lang="scss" scoped>
.content {
  position: relative;
  box-sizing: border-box;
  height: 100vh;
  background: #f3f7f8;

  .bg {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
    width: 750rpx;
    height: 522rpx;
  }
}

.scroll-Y {
  position: relative;
  z-index: 2;
  box-sizing: border-box;
  height: calc(100vh - 172rpx);
  padding: 32rpx;
}

.chat_list {
  padding-bottom: 32rpx;

  .answer,
  .default {
    position: relative;
    padding-top: 92rpx;
    margin-bottom: 32rpx;

    .img_robot {
      position: absolute;
      top: 0;
      left: 0;
      z-index: 1;
      width: 120rpx;
      height: 120rpx;
    }

    .text {
      position: relative;
      z-index: 2;
      padding: 24rpx;
      font-size: 30rpx;
      font-weight: 400;
      line-height: 54rpx;
      color: #222;
      background: #fff;
      border-radius: 0 24rpx 24rpx;
    }
  }

  .question,
  .hospital {
    margin-bottom: 32rpx;
    overflow: hidden;

    .text {
      position: relative;
      z-index: 2;
      display: block;
      float: right;
      padding: 24rpx;
      font-size: 30rpx;
      font-weight: 400;
      line-height: 54rpx;
      color: #fff;
      background: #00d1b6;
      border-radius: 24rpx 0 24rpx 24rpx;
    }
  }
}

.ask_input {
  position: fixed;
  bottom: 0;
  left: 0;
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
  width: 100%;
  padding: 32rpx;
  padding-bottom: calc(32rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(32rpx + env(safe-area-inset-bottom));
  background: #fff;

  input {
    box-sizing: border-box;
    width: 544rpx;
    height: 72rpx;
    padding: 0 30rpx;
    line-height: 72rpx;
    background: #fafafa;
    border-radius: 84rpx;
  }

  .send {
    width: 126rpx;
    height: 72rpx;
    padding: 0 !important;
    margin: 0;
    font-size: 30rpx !important;
    font-weight: 500;
    line-height: 72rpx !important;
    color: #fff !important;
    background: #00d1b6;
    border-radius: 56rpx;
  }
}
</style>
